package com.lovezy.platform.core.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;

/**
 * JSON
 * 工具
 * Created by jin on 2017/12/17.
 */
public final class JsonUtil {

    private static Log log = LogFactory.getLog(JsonUtil.class);

    @Nullable
    public static String toJson(Object o) {
        if(o == null) return null;
        ObjectMapper om = new ObjectMapper();
        try {
            return om.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            log.error("转换JSON异常", e);
        }
        return null;
    }

    @Nullable
    public static <T> T toObject(String json,Class<T> clazz) {
        if(json == null) return null;
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(json, clazz);
        } catch (IOException e) {
            log.error("解析json异常", e);
        }
        return null;
    }

}
